package com.songcan.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.songcan.common.contans.CoreContants;
import com.songcan.common.context.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class AuthorizationFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        log.info("path==:{}",path);
        exchange.getAttributes().remove("cachedRequestBody");
        final Flux<DataBuffer> body = (Flux)exchange.getAttributeOrDefault("cachedRequestBody", (Object)null);
        ServerHttpRequest host =
                exchange.getRequest().mutate().header(CoreContants.CORE_USER, UserContext.getUserId())
                        .header(CoreContants.CORE_ORGANIZATION, JSON.toJSONString(UserContext.getDeptIds()))
                        .header(CoreContants.CORE_ROLE,JSON.toJSONString(UserContext.getRoles())).build();
        //将现在的request 变成 change对象
//                ServerWebExchange build = exchange.mutate().request(host).build();
        exchange = exchange.mutate().request(host).build();
        if (body != null) {
            ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(exchange.getRequest()) {
                public Flux<DataBuffer> getBody() {
                    return body;
                }
            };
            exchange.mutate().request(decorator);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE+2;
    }
}
